package com.dirven.game;

public class Countdown {

	IntervalTimer intTimer;
	long duration,
		 timeRemaining,
		 updateInterval;
	private boolean finished;
	
	public Countdown(long time, long updateInterval) {
		this.timeRemaining = this.duration = time;
		this.updateInterval = updateInterval;
		intTimer = new IntervalTimer(updateInterval);
		finished = false;
	}
	
	/**
	 * Start the countdown.
	 */
	public void start() {
		intTimer.start();
		finished = false;
	}
	
	/**
	 * Update the countdown.
	 */
	private void update() {
		
		/**
		 * If finished countdown stop decrementing the remaining time.
		 */
		if(timeRemaining <= 0) {
			// Stop the countdown.
			stop();
			return;
		}
		
		// If at the next interval decrease the time remaining.
		if(intTimer.atNextInterval()) {
			timeRemaining -= updateInterval;
		}
	}
	
	/**
	 * Gets the remaining time in seconds.
	 * @return
	 */
	public long getTimeRemaining() {
		return timeRemaining/1000;
	}
	
	/**
	 * Get the remaining time formatted.
	 * @return
	 */
	public String getRemainingTimeFormatted() {
		// Update the countdown.
		update();
		
		// Get the seconds remaining
		int seconds = (int) ((timeRemaining / 1000) % 60);
		// Get the minute remaining
		int minutes = (int) ((timeRemaining / 1000) / 60);
		
		String formattedTime;
		
		// Format time
		
		// If remaining time is more than a minute, include minutes and seconds
		if(minutes > 0) {
			formattedTime = minutes+":"+ ((seconds<10)?"0"+seconds:seconds);
		// If remaining time is less than a minute, just display it in seconds.
		} else {
			formattedTime = ""+seconds;
		}
		
		return formattedTime;
	}
	
	/**
	 * Pause the countdown
	 */
	public void pause() {
		intTimer.pause();
	}
	
	/**
	 * Resume the countdown.
	 */
	public void resume() {
		intTimer.resume();
	}
	
	/**
	 * Stop the countdown.
	 */
	public void stop() {
		intTimer.stop();
		finished = true;
	}
	
	/**
	 * Check if the countdown is finished.
	 * @return
	 */
	public boolean isFinished() {
		return finished;
	}
	
	/**
	 * Reset the countdown.
	 */
	public void reset() {
		this.timeRemaining = duration;
		start();
	}
}
